package com.zyt.fullcase.servlet;

import com.zyt.fullcase.domain.User;
import com.zyt.fullcase.domain.UserPageBean;
import com.zyt.fullcase.service.UserService;
import com.zyt.fullcase.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/GetUserPagedListServlet")
public class GetUserPagedListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer page = Integer.valueOf(request.getParameter("page") != null ? request.getParameter("page"): "1");
        Integer contentNumOfPage = Integer.valueOf(request.getParameter("contentNumOfPage") != null ? request.getParameter("contentNumOfPage") : "5");
        if (page <= 0) {
            page = 1;
        }
        if (contentNumOfPage <= 0) {
            contentNumOfPage = 1;
        }

        UserService userService = new UserServiceImpl();
        Integer totalCount = userService.totalCount();
        List<User> users = userService.getUsers(page, contentNumOfPage);

        UserPageBean pageBean = new UserPageBean();
        pageBean.setTotalCount(totalCount);
        pageBean.setTotalPage((int) Math.ceil(totalCount*1.0/contentNumOfPage));
        pageBean.setUsers(users);
        pageBean.setCurrentPage(page);

        request.setAttribute("pageBean", pageBean);
        request.getRequestDispatcher("/pagedList.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
